"""
医疗场景API路由管理器
"""

from fastapi import APIRouter, HTTPException
from typing import List
from pydantic import BaseModel

from medical_scenes.manager import MedicalSceneManager
from medical_scenes.base.models import (
    ClinicalScene, 
    ImageProcessingRequest, 
    ImageProcessingResult
)
from medical_scenes.scenes.lung_nodule.processor import LungNoduleProcessor

# 创建主路由
router = APIRouter(prefix="/api/medical-scenes", tags=["medical-scenes"])

# 初始化场景管理器
scene_manager = MedicalSceneManager()

class TaskInfo(BaseModel):
    """任务信息模型"""
    id: str
    name: str
    description: str
    icon: str

# 统一处理接口
@router.post("/process", response_model=ImageProcessingResult)
async def process_medical_scene(request: ImageProcessingRequest):
    """
    统一处理接口
    
    Args:
        request: 图像处理请求
        
    Returns:
        ImageProcessingResult: 处理结果
    """
    try:
        # 处理场景
        results = scene_manager.process_scene(
            request.scene_id, 
            request.image_data, 
            **request.parameters
        )
        
        # 构造响应
        response = ImageProcessingResult(
            success=True,
            scene_id=request.scene_id,
            results=results
        )
        
        return response
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")

# 用于调试，检查场景列表
@router.get("/scenes", response_model=List[ClinicalScene])
async def list_scenes():
    """
    获取所有场景列表
    
    Returns:
        List[ClinicalScene]: 场景列表
    """
    try:
        scenes = scene_manager.list_scenes()
        return scenes
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list scenes: {str(e)}")

@router.get("/scenes/{scene_id}", response_model=ClinicalScene)
async def get_scene_info(scene_id: str):
    """
    获取特定场景信息
    
    Args:
        scene_id: 场景ID
        
    Returns:
        ClinicalScene: 场景信息
    """
    try:
        scenes = scene_manager.list_scenes()
        for scene in scenes:
            if scene["id"] == scene_id:
                return scene
        
        raise HTTPException(status_code=404, detail=f"Scene '{scene_id}' not found")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to get scene info: {str(e)}")

@router.get("/scenes/{scene_id}/tasks", response_model=List[TaskInfo])
async def list_scene_tasks(scene_id: str):
    """
    获取特定场景下的任务列表
    
    Args:
        scene_id: 场景ID
        
    Returns:
        List[TaskInfo]: 任务列表
    """
    try:
        # 目前只支持肺结节场景
        if scene_id == "lung-nodule":
            processor = LungNoduleProcessor()
            tasks = processor.get_tasks()
            return [TaskInfo(**task) for task in tasks]
        
        raise HTTPException(status_code=404, detail=f"Scene '{scene_id}' not found or has no tasks")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Failed to list scene tasks: {str(e)}")

# 在main.py注册各场景的特定路由,用于直接调用特定场景的接口，至少可以用来测试单个场景是否正确，然后再合并到统一接口中使用
def register_scene_routes(app):
    """
    注册各场景的特定路由。
    可以用来测试单个场景是否正确，然后再合并到统一接口中使用。

    Args:
        app: FastAPI应用实例
    """
    try:
        # 导入并注册肺结节场景路由
        from medical_scenes.scenes.lung_nodule.api import router as lung_nodule_router
        app.include_router(lung_nodule_router)
    except Exception as e:
        pass
